const AppError = require("../../utils/appError")
const userFriendMid = require('../../model/userFriendMid');
const UserInfo = require('../../model/userinfo');
const userFriendsConfirm = require("../../model/userFriendsConfirm")
const { ServerGetUSerInfoList, ServerGetUserInfo } = require("../user/index")
const { Op } = require("sequelize");
const sequelize = require("../../model/index")
const { getUuid } = require("../../utils/index")
module.exports = {
    ServerFindCommendFriends: async (userAccount) => {
        const FriendMid = userFriendMid.findAll({
            where: {
                [Op.and]: {
                    [Op.or]: [
                        { friendUserId1: userAccount },
                        { friendUserId2: userAccount },
                    ],
                    friendsTypes: 1
                }
            },
            raw: true
        })
        const FriendsConfirm = userFriendsConfirm.findAll({
            where: {
                [Op.and]: {
                    [Op.or]: [
                        { userId: userAccount },
                        { friendUserId: userAccount }
                    ],
                    isConfirm: {
                        [Op.notIn]: [2]
                    }
                }
            },
            attributes: ["friendUserId", "userId"],
            raw: true
        })
        const [FriendMidres, FriendsConfirmRes] = await Promise.all([FriendMid, FriendsConfirm])
        const friendlist = FriendMidres.map((item) => {
            if (item.friendUserId1 == userAccount) {
                return item.friendUserId2
            }
            if (item.friendUserId2 == userAccount) {
                return item.friendUserId1
            }
        })
        const UserInfores = await UserInfo.findAll({
            where: {
                id: {
                    [Op.notIn]: [...friendlist, userAccount, ...FriendsConfirmRes.map(item => item.friendUserId == userAccount ? item.userId : item.friendUserId)]
                }
            },
            limit: 20,
            raw: true
        })
        if (UserInfores) {
            return {
                isok: 1,
                data: UserInfores,
                message: "查询成功"
            }
        } else {
            return {
                isok: 0,
                data: {},
                message: "查询失败"
            }
        }
    },
    ServerMakeFriend: async (data) => {
        const res = await userFriendsConfirm.findOne({
            where: {
                [Op.and]: [
                    { userId: data.userId },
                    { friendUserId: data.friendUserId },
                    { isConfirm: 2 }
                ]
            },
            raw: true
        })
        if (!res) {
            const FriendsConfirm = await userFriendsConfirm.create(data)
            if (FriendsConfirm) {
                return {
                    isok: 1,
                    data: FriendsConfirm.dataValues,
                    message: "创建成功"
                }
            }
        } else {
            const FriendsConfirm = await userFriendsConfirm.update({ isConfirm: 3 }, {
                where: {
                    [Op.and]: [
                        { userId: data.userId },
                        { friendUserId: data.friendUserId }
                    ]
                }
            })
            if (FriendsConfirm) {
                return {
                    isok: 1,
                    data: FriendsConfirm.dataValues,
                    message: "创建成功"
                }
            }

        }
        return {
            isok: 0,
            data: {},
            message: "失败"
        }
    },
    ServerMakeFindFriends: async (ids) => {
        const FriendsConfirm = await userFriendsConfirm.findOne({
            where: {
                [Op.or]: [
                    {
                        userId: ids.id1,
                        friendUserId: ids.id2,
                        isConfirm: {
                            [Op.not]: 2,
                        }
                    }, {
                        userId: ids.id2,
                        friendUserId: ids.id1,
                        isConfirm: {
                            [Op.not]: 2,
                        }
                    }
                ]
            },
            raw: true
        })
        if (FriendsConfirm) {
            return {
                isok: 0,
                data: FriendsConfirm,
                message: "已有好友添加记录"
            }
        }
        return {
            isok: 1,
            data: {},
            message: "暂无好友添加记录"
        }
    },
    ServerGetApplyFriends: async (userId) => {
        const GetApplyFriendsres = await userFriendsConfirm.findAll({
            where: {
                [Op.and]: [
                    { friendUserId: userId },
                    { isConfirm: 3 }
                ]
            },
            raw: true,
            attributes: ["userId", "commentInfo"],
        })
        if (GetApplyFriendsres.length) {
            const res = await ServerGetUSerInfoList(GetApplyFriendsres.map(item => item.userId))
            if (res.isok) {
                return {
                    isok: 1,
                    data: res.data.map(item => {
                        return {
                            ...item,
                            commentInfo: GetApplyFriendsres.find(data => data.userId == item.id)['commentInfo']
                        }
                    }),
                    message: res.message
                }
            }
            return {
                isok: 0,
                data: {},
                message: res.message
            }
        }
        return {
            isok: 0,
            data: {},
            message: "暂无数据"
        }
    },
    ServerRejectFriends: async (userId, friendUserId) => {
        const res = await userFriendsConfirm.findOne({
            where: {
                [Op.and]: [
                    { userId: userId },
                    { friendUserId: friendUserId }
                ]
            },
            raw: true
        })
        if (res) {
            const FriendsConfirmres = await userFriendsConfirm.update({
                isConfirm: 2
            }, {
                where: {
                    [Op.and]: [
                        { userId },
                        { friendUserId }
                    ]
                },
                raw: true
            })
            if (FriendsConfirmres) {
                return {
                    isok: 1,
                    data: true,
                    message: "成功"
                }
            }
            return {
                isok: 0,
                data: false,
                message: "修改失败"
            }
        }
        return {
            isok: 0,
            data: false,
            message: "暂未添加对方"
        }
    },
    ServerConfirmFirends: async ({ userId, friendUserId, commendName }) => {
        const userFriends = userFriendsConfirm.findOne({
            where: {
                [Op.and]: [
                    { userId: userId },
                    { friendUserId: friendUserId }
                ]
            },
            raw: true
        })
        const userFriend = userFriendMid.findOne({
            where: {
                [Op.or]: [{
                    [Op.and]: [
                        { friendUserId1: userId },
                        { friendUserId2: friendUserId }
                    ]
                }, {
                    [Op.and]: [
                        { friendUserId2: userId },
                        { friendUserId1: friendUserId }
                    ]
                }]
            },
            raw: true
        })
        const [res1, res2] = await Promise.all([userFriends, userFriend])
        if (res1 && !res2) {
            const t = await sequelize.transaction();
            try {
                const friendsconfirm = userFriendsConfirm.update({
                    isConfirm: 1
                }, {
                    where: {
                        [Op.and]: [
                            { userId: userId },
                            { friendUserId: friendUserId }
                        ]
                    }
                }, { transaction: t })
                const userfriendmid = userFriendMid.create({
                    friendUserId1: userId,
                    friendUserId2: friendUserId,
                    commendName2: commendName,
                    friendsTypes: 1,
                    showMessage: true,
                    showMessage1: true,
                    showMessage2: true,
                    noMessageNum1: 1,
                    noMessageNum2: 1,
                    friendMessageId: getUuid()
                }, { transaction: t })
                const [friendsconfirmres, userfriendmidres] = await Promise.all([friendsconfirm, userfriendmid])
                if (friendsconfirmres && userfriendmidres) {
                    // 提交事务.
                    await t.commit();
                    return {
                        isok: 1,
                        data: true,
                        message: "成功"
                    }
                } else {
                    await t.rollback();
                    return {
                        isok: 0,
                        data: false,
                        message: "添加失败"
                    }
                }
            } catch (error) {
                new AppError({
                    errorInfo: "好友添加失败",
                    statusCode: 400,
                })
                // 回滚事务.
                await t.rollback();
            }
        }
        if (!res1) {
            return {
                isok: 0,
                data: {},
                message: "暂未添加对方"
            }
        }
        if (res2) {
            return {
                isok: 0,
                data: {},
                message: "已经添加对方"
            }
        }
    },
    ServerGetFriendsList: async (userId) => {
        const userFriendList = await userFriendMid.findAll({
            where: {
                [Op.and]: {
                    [Op.or]: [
                        { friendUserId1: userId },
                        { friendUserId2: userId },
                    ],
                    friendsTypes: 1
                },
            },
            raw: true
        })
        if (userFriendList.length) {
            const userIdlist = userFriendList.map(item =>
                item.friendUserId1 == userId ? {
                    userid: item.friendUserId2,
                    commendName: item.commendName1,
                    showMessage: item.showMessage1,
                    noMessageNum: item.noMessageNum1,
                    messageLastdate: item.messageLastdate,
                    messageId: item.id,

                } : {
                    userid: item.friendUserId1,
                    commendName: item.commendName2,
                    showMessage: item.showMessage2,
                    noMessageNum: item.noMessageNum2,
                    messageLastdate: item.messageLastdate,
                    messageId: item.id
                })
            const friendlist = await UserInfo.findAll({
                where: {
                    id: {
                        [Op.in]: userIdlist.map(item => item.userid)
                    }
                },
                raw: true
            })
            if (friendlist.length) {
                return {
                    isok: 1,
                    data: friendlist.map(item => {
                        return {
                            ...item,
                            commendName: userIdlist.find(data => data.userid == item.id)["commendName"],
                            showMessage: userIdlist.find(data => data.userid == item.id)["showMessage"],
                            messageLastdate: userIdlist.find(data => data.userid == item.id)["messageLastdate"],
                            noMessageNum: userIdlist.find(data => data.userid == item.id)['noMessageNum'],
                            messageId: userIdlist.find(data => data.userid == item.id)['messageId'],
                        }
                    }),
                    message: "成功"
                }
            }
            return {
                isok: 0,
                data: [],
                message: "失败"
            }
        }
        return {
            isok: 1,
            message: "暂无好友",
            data: []
        }
    },
    ServerGetFriendsDetil: async (userId, friendUserId) => {
        const userFriend = await userFriendMid.findOne({
            where: {
                [Op.and]: {
                    [Op.or]: [
                        {
                            [Op.and]: [
                                { friendUserId1: userId },
                                { friendUserId2: friendUserId },
                            ]
                        },
                        {
                            [Op.and]: [
                                { friendUserId1: friendUserId },
                                { friendUserId2: userId },
                            ]
                        }
                    ],
                    friendsTypes: 1
                },
            },
            raw: true
        })
        if (userFriend) {
            const commendName = userFriend.friendUserId2 == userId ? userFriend.commendName2 : userFriend.commendName1
            const GetUserInfores = await ServerGetUserInfo(friendUserId, true);
            if (GetUserInfores.isok) {
                return {
                    isok: 1,
                    message: "成功",
                    data: {
                        ...GetUserInfores.data,
                        commendName,
                        messageId: userFriend.id
                    }
                }
            }
            return {
                isok: 0,
                data: {},
                message: "失败",
            }
        }
        return {
            isok: 0,
            message: "双方还不是好友",
            data: {}
        }
    },
    ServerFriendsCommend: async (commendName, userId, friendUserId) => {
        const userFriendres = await userFriendMid.findOne({
            where: {
                [Op.or]: [{
                    [Op.and]: [
                        { friendUserId1: userId },
                        { friendUserId2: friendUserId }
                    ]
                }, {
                    [Op.and]: [
                        { friendUserId2: userId },
                        { friendUserId1: friendUserId }
                    ]
                }]
            },
            raw: true
        });
        if (userFriendres) {
            let res
            if (userFriendres.friendUserId2 == userId) {
                res = await userFriendMid.update({ commendName2: commendName }, {
                    where: {
                        [Op.or]: [{
                            [Op.and]: [
                                { friendUserId1: userId },
                                { friendUserId2: friendUserId }
                            ]
                        }, {
                            [Op.and]: [
                                { friendUserId2: userId },
                                { friendUserId1: friendUserId }
                            ]
                        }]
                    },
                })
            } else {
                res = await userFriendMid.update({ commendName1: commendName }, {
                    where: {
                        [Op.or]: [{
                            [Op.and]: [
                                { friendUserId1: userId },
                                { friendUserId2: friendUserId }
                            ]
                        }, {
                            [Op.and]: [
                                { friendUserId2: userId },
                                { friendUserId1: friendUserId }
                            ]
                        }]
                    },
                })
            }
            if (res) {
                return {
                    isok: 1,
                    message: "成功",
                    data: true
                }
            }
            return {
                isok: 0,
                message: "失败",
                data: false
            }
        }
        return {
            isok: 1,
            message: "暂无好友",
            data: false
        }
    },
    ServerDeleteFriends: async (userId, friendUserId) => {
        const t = await sequelize.transaction();
        try {
            const [FriendMires, FriendsConfirmres] = await Promise.all([userFriendMid.destroy({
                where: {
                    [Op.or]: [{
                        [Op.and]: [
                            { friendUserId1: userId },
                            { friendUserId2: friendUserId }
                        ]
                    }, {
                        [Op.and]: [
                            { friendUserId2: userId },
                            { friendUserId1: friendUserId }
                        ]
                    }]
                }
            }, {
                transaction: t
            }), userFriendsConfirm.destroy({
                where: {
                    [Op.or]: [{
                        [Op.and]: [
                            { userId: userId },
                            { friendUserId: friendUserId }
                        ]
                    }, {
                        [Op.and]: [
                            { friendUserId: userId },
                            { userId: friendUserId }
                        ]
                    }]
                }

            }, {
                transaction: t
            })])
            if (FriendMires & FriendsConfirmres) {
                await t.commit();
                return {
                    isok: 1,
                    message: "删除成功",
                    data: true
                }
            } else {
                // 回滚事务.
                await t.rollback();
                return {
                    isok: 0,
                    message: "失败",
                    data: false
                }
            }
        } catch (error) {
            console.log(error);
            // 回滚事务.
            await t.rollback();
            return {
                isok: 0,
                message: "失败",
                data: false
            }
        }

    },
    ServerSearchFriends: async (userId, searchvalue) => {
        const userFriendres = await userFriendMid.findAll({
            where: {
                [Op.and]: {
                    [Op.or]: {
                        friendUserId1: userId,
                        friendUserId2: userId,
                    },
                    friendsTypes: 1,
                }
            },
            raw: true
        });
        if (userFriendres.length) {
            const userIdlist = userFriendres.map(item => {
                return {
                    id: item.friendUserId1 == userId ? item.friendUserId2 : item.friendUserId1,
                    commendName: item.friendUserId1 == userId ? item.commendName1 : item.commendName2
                }
            })
            const friendlist = await UserInfo.findAll({
                where: {
                    id: {
                        [Op.in]: userIdlist.map(item => item.id)
                    }
                },
                raw: true
            })
            if (friendlist.length) {
                const list = friendlist.map(item => {
                    return {
                        ...item,
                        commendName: userIdlist.find(data => data.id == item.id)["commendName"]
                    }
                }).filter(item => {
                    if (item.commendName && item.commendName?.indexOf(searchvalue) != -1) {
                        return true
                    }
                    if (item.userName.indexOf(searchvalue) != -1) {
                        return true
                    }
                    return false
                })
                return {
                    isok: 1,
                    data: list,
                    message: "成功"
                }
            }
            return {
                isok: 0,
                data: [],
                message: "失败"
            }
        }
        return {
            isok: 1,
            message: "暂无好友",
            data: []
        }
    },
    ServerGetFriends: async ({ userId, friendUserId }) => {
        const res = await userFriendMid.findOne({
            where: {
                friendUserId1: userId,
                friendUserId2: friendUserId,
            },
            raw: true
        })
        if (res) {
            return {
                isok: 1,
                message: "查询成功",
                data: res
            }
        }
        return {
            isok: 0,
            message: "查询失败",
            data: {}
        }
    },
    ServerUpdataFriendMessageId: async (id, userId, friendUserId) => {
        const res = await userFriendMid.update({
            messageLastdate: id
        }, {
            where: {
                friendUserId1: userId,
                friendUserId2: friendUserId,
            }
        })
        if (res) {
            return {
                isok: 1,
                message: "更新时间成功",
                data: true
            }
        }
        return {
            isok: 0,
            message: "更新时间失败",
            data: false
        }
    },
    GetFriend: async (userId, messageId) => {
        const userinfo = await userFriendMid.findOne({
            where: {
                id: messageId
            }
        }, { raw: true });
        const friendId = userId == userinfo.friendUserId1 ? userinfo.friendUserId2 : userinfo.friendUserId1;
        const info = await UserInfo.findOne({
            where: {
                id: friendId
            }
        }, { raw: true })
        const user = {
            id: info.id,
            name: userId == userinfo.friendUserId1 ? userinfo.commendName1 ? userinfo.commendName1 : info.userName : userinfo.commendName2 ? userinfo.commendName2 : info.userName,
            avatar: info.userAvatar,
        }
        if (info) {
            return {
                isok: 1,
                message: "获取朋友成功",
                data: user
            }
        }
        return {
            isok: 0,
            message: "获取朋友失败",
            data: {}
        }
    }
}